<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>角色管理</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="css/style.css">
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <!-- Bootstrap 5 Modal 脚本依赖 -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

</head>
<body>

    <div class="card p-4">
        <h2 class="mb-4">角色列表</h2>

        <!-- 控件：每页条数选择 + 跳转页 -->
        <div class="row mb-3">
            <div class="col-md-6 mb-2">
                <label>每页显示：
                    <select id="pageSizeSelect" class="form-select d-inline-block w-auto">
                        <option value="5">5 条</option>
                        <option value="10">10 条</option>
                        <option value="20">20 条</option>
                    </select>
                </label>
            </div>
            <div class="col-md-6 mb-2 text-end">
                <label>跳转到第 <input id="jumpPageInput" type="number" min="1" class="form-control d-inline-block w-auto"> 页
                    <button id="jumpPageBtn" class="btn btn-outline-primary btn-sm ms-2">跳转</button>
                </label>
            </div>
        </div>

        <!-- 表格 -->
        <table class="table table-hover table-bordered text-center">
            <thead class="table-light">
            <tr>
                <th>角色ID</th>
                <th>角色名称</th>
                <th>描述</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="roleTableBody"></tbody>
        </table>

        <!-- 分页 -->
        <nav class="pagination-controls">
            <ul id="pagination" class="pagination justify-content-center pagination-custom mb-0">
                <!-- 分页按钮自动生成 -->
            </ul>
        </nav>
    </div>


<script>
    let currentPage = 1;
    let pageSize = 5;
    let totalPages = 1;

    function loadData(page) {
        $.ajax({
            url: '/system/sysRole/page',
            method: 'GET',
            dataType: 'json',
            data: {
                current: page,
                size: pageSize
            },
            success: function (response) {
                const $tbody = $('#roleTableBody');
                $tbody.empty();

                response.records.forEach(role => {
                    const row = `
                        <tr>
                            <td>${role.roleId}</td>
                            <td>${role.roleName}</td>
                            <td>${role.description}</td>
                            <td class="action-btns">
                                <button class="btn btn-sm btn-warning edit-btn" data-id="${role.roleId}">编辑</button>
                                <button class="btn btn-sm btn-danger delete-btn" data-id="${role.roleId}">删除</button>
                            </td>
                        </tr>`;
                    $tbody.append(row);
                });

                currentPage = response.current;
                totalPages = response.pages;

                renderPagination(currentPage, totalPages);
            },
            error: function () {
                alert('加载失败，请检查接口。');
            }
        });
    }

    function renderPagination(current, total) {
        const $pagination = $('#pagination');
        $pagination.empty();

        // 上一页
        $pagination.append(`
            <li class="page-item ${current === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${current - 1}">上一页</a>
            </li>
        `);

        // 页码
        const start = Math.max(1, current - 2);
        const end = Math.min(total, current + 2);
        for (let i = start; i <= end; i++) {
            $pagination.append(`
                <li class="page-item ${i === current ? 'active' : ''}">
                    <a class="page-link" href="#" data-page="${i}">${i}</a>
                </li>
            `);
        }

        // 下一页
        $pagination.append(`
            <li class="page-item ${current === total ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${current + 1}">下一页</a>
            </li>
        `);
    }

    $(document).ready(function () {
        loadData(currentPage);

        // 分页点击
        $('#pagination').on('click', 'a', function (e) {
            e.preventDefault();
            const page = parseInt($(this).data('page'));
            if (page >= 1 && page <= totalPages) {
                loadData(page);
            }
        });

        // 每页条数更改
        $('#pageSizeSelect').change(function () {
            pageSize = parseInt($(this).val());
            currentPage = 1;
            loadData(currentPage);
        });

        // 跳转页
        $('#jumpPageBtn').click(function () {
            const page = parseInt($('#jumpPageInput').val());
            if (!isNaN(page) && page >= 1 && page <= totalPages) {
                loadData(page);
            }
        });

        // 编辑按钮
        let editModal = new bootstrap.Modal(document.getElementById('editModal'));

// 点击编辑按钮，填充数据并弹出模态框
        $('#roleTableBody').on('click', '.edit-btn', function () {
            const roleId = $(this).data('id');

            // 获取单个角色数据
            $.ajax({
                url: '/system/sysRole/' + roleId,
                method: 'GET',
                success: function (role) {
                    $('#editRoleId').val(role.roleId);
                    $('#editRoleName').val(role.roleName);
                    $('#editDescription').val(role.description);
                    editModal.show();
                },
                error: function () {
                    alert('获取角色信息失败');
                }
            });
        });

// 保存编辑内容
        $('#saveEditBtn').click(function () {
            const roleData = {
                roleId: $('#editRoleId').val(),
                roleName: $('#editRoleName').val(),
                description: $('#editDescription').val()
            };

            $.ajax({
                url: '/system/sysRole/update',
                method: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify(roleData),
                success: function () {
                    alert('更新成功');
                    editModal.hide();
                    loadData(currentPage);
                },
                error: function () {
                    alert('更新失败，请检查接口');
                }
            });
        });


        // 删除按钮
        $('#roleTableBody').on('click', '.delete-btn', function () {
            const roleId = $(this).data('id');
            if (confirm('确定要删除此角色吗？')) {
                $.ajax({
                    url: '/system/sysRole/delete/' + roleId,
                    method: 'DELETE',
                    success: function () {
                        alert('删除成功');
                        loadData(currentPage);
                    },
                    error: function () {
                        alert('删除失败，请检查接口');
                    }
                });
            }
        });
    });
</script>
<!-- 编辑模态框 -->
<div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editModalLabel">编辑角色</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
            </div>
            <div class="modal-body">
                <form id="editForm">
                    <input type="hidden" id="editRoleId">
                    <div class="mb-3">
                        <label for="editRoleName" class="form-label">角色名称</label>
                        <input type="text" class="form-control" id="editRoleName" required>
                    </div>
                    <div class="mb-3">
                        <label for="editDescription" class="form-label">描述</label>
                        <textarea class="form-control" id="editDescription" rows="3"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveEditBtn">保存</button>
            </div>
        </div>
    </div>
</div>

</body>
</html>
